package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.Bank;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class BankServer {
    public static void startServer(Bank bank) {
        try(ServerSocket ss = new ServerSocket(9900)) {
            while(true) {
                String command;
                try(Socket client = ss.accept()) {
                    try(DataInputStream dis = new DataInputStream(client.getInputStream());
                    DataOutputStream dos = new DataOutputStream(client.getOutputStream())) {
                        System.out.println("Client connected");
                        while(true) {
                            command = dis.readUTF();
                            System.out.println("Command>>" + command);
                            switch(command.toLowerCase()) {
                                case "exit":
                                    client.close();
                                    break;
                                case "br":
                                    dos.writeUTF(BankReport.reportBalance(bank));
                                    break;
                                case "wdr":
                                    dos.writeUTF(BankReport.printMaximumAmountToWithdraw(bank));
                                    break;
                                default:
                                    dos.writeUTF("Incorrect command");
                                    break;
                            }
                        }
                    } catch(IOException e) {
                        System.out.println("Client disconnected");
                    }
                } catch(IOException e) {
                    e.printStackTrace();
                }
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}
